package com.aiyige.page.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.eventbus.EventLogin;
import com.aiyige.model.Country;
import com.aiyige.page.login.presenter.LoginPresenter;
import com.aiyige.page.login.view.ILoginView;
import com.aiyige.utils.AppUtils;
import com.aiyige.utils.UIHelper;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.umeng.socialize.UMShareAPI;

import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.aiyige.page.login.SelectCountryPage.COUNTRY_REQUEST_CODE;

@Route(path = ARouterConfig.LoginPage)
public class LoginPage extends BaseActivity implements ILoginView {
    public static final String TAG = LoginPage.class.getSimpleName();
    @BindView(R.id.tv_county_name)
    TextView countryName;
    @BindView(R.id.tv_county_number)
    TextView countryNumber;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.et_username)
    EditText etLoginUsername;
    @BindView(R.id.iv_password_visible)
    ImageView ivPasswordVisible;
    @BindView(R.id.rl_password_visible)
    RelativeLayout rlPasswordVisible;
    @BindView(R.id.et_login_password)
    EditText etLoginPassword;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.tv_forget_password)
    TextView tvForgetPassword;
    @BindView(R.id.iv_login_wechat)
    ImageView ivLoginWechat;
    @BindView(R.id.iv_login_qq)
    ImageView ivLoginQq;
    @BindView(R.id.iv_login_blog)
    ImageView ivLoginBlog;

    @BindView(R.id.ll_top)
    LinearLayout llTop;

    Country selectedCountry;
    @Autowired
    String targetPage = null;
    @Autowired
    Bundle targetData = null;
    boolean isPasswordVisible = false;

    private LoginPresenter presenter = new LoginPresenter(this);


    public static void start() {
        ARouter.getInstance().build(ARouterConfig.LoginPage).navigation();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_login);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        etLoginUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                checkUserInput();
            }
        });
        etLoginPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                checkUserInput();
            }
        });
        etLoginPassword.setImeOptions(EditorInfo.IME_ACTION_DONE);
        etLoginPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE
                        || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    presenter.login();
                    return true;
                }
                return false;
            }
        });
        checkUserInput();
        setAutoRegisterEventBus(true);
        // 键盘显示隐藏监听
        AppUtils.addOnSoftKeyBoardVisibleListener(this, new AppUtils.SoftKeyBoardCallback() {
            @Override
            public void show() {
                RelativeLayout.LayoutParams ll  = (RelativeLayout.LayoutParams) llTop.getLayoutParams();
                ll.setMargins(0, UIHelper.dip2px(LoginPage.this,-40), 0, 0);
                llTop.setLayoutParams(ll);
            }

            @Override
            public void hide() {
                RelativeLayout.LayoutParams ll  = (RelativeLayout.LayoutParams) llTop.getLayoutParams();
                ll.setMargins(0, UIHelper.dip2px(LoginPage.this,0), 0, 0);
                llTop.setLayoutParams(ll);
            }
        });
    }

    private void checkUserInput() {
        boolean userInputEmpty = false;
        if (isEmpty(getUserName()) || isEmpty(getPassword())) {
            userInputEmpty = true;
        }

        // 如果用户名或面为空，则登录按钮不可点
        btnLogin.setEnabled(!userInputEmpty);
    }


    @Override
    public String getUserName() {
        return etLoginUsername.getText().toString().trim();
    }

    @Override
    public String getPassword() {
        return etLoginPassword.getText().toString().trim();
    }

    @Override
    public void clearUserName() {

    }

    @Override
    public void clearPassword() {

    }

    @Override
    public void showLoading() {
        super.showLoading();
    }

    @Override
    public void hideLoading() {
        super.hideLoading();
    }

    @Override
    public String getTargetPage() {
        return targetPage;
    }

    @Override
    public Bundle getTargetData() {
        return targetData;
    }

    @Subscribe
    public void onLoginEvent(EventLogin event) {
        finish();
    }


    @OnClick({R.id.rl_back, R.id.tv_login, R.id.tv_register, R.id.tv_county_name, R.id.tv_county_number, R.id.iv_password_visible, R.id.rl_password_visible, R.id.btn_login, R.id.tv_forget_password, R.id.iv_login_wechat, R.id.iv_login_qq, R.id.iv_login_blog})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_back:
                finish();
                break;
            case R.id.tv_register:
                ARouter.getInstance().build(ARouterConfig.RegisterPage).navigation();
                break;
            case R.id.tv_county_name:
            case R.id.tv_county_number:
//                ARouter.getInstance().build(ARouterConfig.SelectCountryPage)
//                        .navigation(this, COUNTRY_REQUEST_CODE);
                break;
            case R.id.iv_password_visible:
            case R.id.rl_password_visible:
                isPasswordVisible = !isPasswordVisible;
                ivPasswordVisible.setImageResource(isPasswordVisible ? R.drawable.login_eye_y : R.drawable.login_eye_n);
                etLoginPassword.setTransformationMethod(isPasswordVisible ? HideReturnsTransformationMethod.getInstance() : PasswordTransformationMethod.getInstance());
                etLoginPassword.setSelection(isEmpty(getPassword()) ? 0 : getPassword().length());
                break;
            case R.id.btn_login:

                presenter.login();
                break;
            case R.id.tv_forget_password:
                ARouter.getInstance().build(ARouterConfig.FindPasswordPage).navigation();
                break;
            case R.id.iv_login_wechat:
                presenter.loginWeChat(LoginPage.this);
                break;
            case R.id.iv_login_qq:
                presenter.loginQQ(LoginPage.this);
                break;
            case R.id.iv_login_blog:
                presenter.loginWeibo(LoginPage.this);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (COUNTRY_REQUEST_CODE == requestCode) {
            Country country;
            try {
                country = (Country) data.getSerializableExtra("country");
                setCountry(country);
            } catch (Exception e) {

            }
        }

    }

    //    qq微信新浪授权防杀死
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        UMShareAPI.get(this).onSaveInstanceState(outState);
    }


    private void setCountry(Country country) {
        this.selectedCountry = country;
        countryName.setText(selectedCountry.getCountryName());
        countryNumber.setText(selectedCountry.getPhoneCode());
    }
}
